﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using log4net;
using System.Collections.Generic;
using Microsoft.Reporting.WebForms;
using System.Diagnostics;
using System.Data.SqlClient;

public partial class timeTracking : System.Web.UI.Page
{
    #region Instant
    //inject EmployeeBLL
    private IEmployeeBLL empBLL = Factory<IEmployeeBLL>.CreateInstance();

    //Inject log4net
    private static readonly ILog logger = LogManager.GetLogger(typeof(timeTracking).Name); 
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        //get id from context
        if (this.Context.Items["employeeID"] != null && this.Context.Items["Working"] != null)
        {
            Inits(this.Context.Items["employeeID"].ToString(), (Working)this.Context.Items["Working"]);
        }
    }


    /// <summary>
    /// Init form
    /// </summary>
    /// <param name="id"></param>
    private void Inits(string employeeId,Working working)
    {
        try
        {
            List<Working> list;
            Employee emp = null;
            if (Utils.IsGuid(employeeId))
            {
                list = empBLL.GetWorkingByEmployee(new Guid(employeeId), working);
                if (list.Count > 0)
                {
                    //set to employee control 
                    emp = new Employee();
                    emp = list.First().Employee;
                    lblCode.Text = emp.Code;
                    lblFullName.Text = emp.FirstName + Constants.SPACE + emp.LastName;
                    lblUser.Text = emp.UserName;
                    lblPosition.Text = emp.Position;
                    //bind to Grid
                    rptTracking.DataSource = list;
                    rptTracking.DataBind();
                }               
            }

            //get employee by Id
            Employee emp2= empBLL.GetById(new Guid(employeeId));
            //save to viewstate to export report
            ViewState["Working"] = working;
            ViewState["Employee"] = emp2;
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }

    public void ExportTimeTracking()
    {
        //Check viewstate
        if(ViewState["Working"]==null)
            return;
        if(ViewState["Employee"]==null)
            return;

        Working work = (Working)ViewState["Working"];
        Employee emp=(Employee)ViewState["Employee"];

        try
        {
            //sql
            string sql = @"SELECT 
                                ShiftName,LoginTime,LogoutTime 
                            from
                                Working W,Employee E 
                            WHERE
                                W.EmployeeID =E.EmployeeID
                                AND W.EmployeeID =@EmployeeID
                                AND LoginTime >= @FromDate
                                AND LoginTime <= @ToDate";
            //parms
            SqlParameter[] parms = new SqlParameter[]{
                    new SqlParameter("@FromDate",work.LoginTime),
                    new SqlParameter("@ToDate",work.LogoutTime),
                    new SqlParameter("@EmployeeID",emp.Id)
                };

            DataTable dt = SqlHelper.ExecuteDataset(CommandType.Text, sql,parms).Tables[0];
            ExportReport("TimeTracking", "AutoParkingDataSet_Working", dt,Constants.REPORT_TIME_TRACKING);     
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }


    private void ExportReport(string fileName, string dataSourceName, DataTable dataSource, string rdlcFile)
    {
        try
        {
            //Check viewstate
            if (ViewState["Working"] == null)
                return;
            if (ViewState["Employee"] == null)
                return;

            Working work = (Working)ViewState["Working"];
            Employee emp = (Employee)ViewState["Employee"];

            LocalReport localReport = new LocalReport();
            localReport.ReportPath = HttpContext.Current.Server.MapPath(Constants.REPORT_PATH + rdlcFile);

            //params
            ReportParameter fromDate = new ReportParameter("FromDate", work.LoginTime.ToString(Constants.DATE_PATTERN));
            ReportParameter toDate = new ReportParameter("ToDate", work.LogoutTime.ToString(Constants.DATE_PATTERN));
            ReportParameter fullName = new ReportParameter("FullName", emp.FirstName+Constants.SPACE+emp.LastName);
            ReportParameter code = new ReportParameter("Code", emp.Code);
            localReport.SetParameters(new ReportParameter[] { fromDate, toDate, fullName, code });




            ReportDataSource reportDataSource = new ReportDataSource(dataSourceName, dataSource);
            //Clear datasource
            localReport.DataSources.Clear();
            localReport.DataSources.Add(reportDataSource);

            string reportType = "PDF";
            string mimeType;
            string encoding;
            string fileNameExtension;
            string deviceInfo =

            "<DeviceInfo>" +
            "  <OutputFormat>PDF</OutputFormat>" +
            "  <PageWidth>8.5in</PageWidth>" +
            "  <PageHeight>11in</PageHeight>" +
            "  <MarginTop>0.3in</MarginTop>" +
            "  <MarginLeft>0.5in</MarginLeft>" +
            "  <MarginRight>0.5in</MarginRight>" +
            "  <MarginBottom>0.1in</MarginBottom>" +
            "</DeviceInfo>";

            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;

            //Render the report
            renderedBytes = localReport.Render(reportType,
                                                deviceInfo,
                                                out mimeType,
                                                out encoding,
                                                out fileNameExtension,
                                                out streams,
                                                out warnings);
            //Clear the response stream and write the bytes to the outputstream
            //Set content-disposition to "attachment" so that user is prompted to take an action
            //on the file (open or save)
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + fileNameExtension);
            Response.BinaryWrite(renderedBytes);
            Response.End();
        }
        catch (Exception)
        {
            throw;
        }
    }

    protected void rptTracking_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lblTotal = (Label)e.Item.FindControl("lblTotal");
            HiddenField hdnFrom = (HiddenField)e.Item.FindControl("hdnFrom");
            HiddenField hdnTo = (HiddenField)e.Item.FindControl("hdnTo");
            DateTime from = DateTime.ParseExact(hdnFrom.Value.Trim(), Constants.DATE_TIME_PATTERN, null);
            DateTime to = DateTime.ParseExact(hdnTo.Value.Trim(), Constants.DATE_TIME_PATTERN, null);
            lblTotal.Text = (to - from).ToString();
        }
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        ExportTimeTracking();
    }
}
